<template>
	<div>
		<el-container style="position: absolute;top: 55px;left: 0;right: 0;bottom: 0;">
			<el-header class="d-flex align-items-center border-bottom">
				<!-- header -->
				<div class="d-flex mr-auto ">
					<el-select v-model="searchForm.order" placeholder="图片排序方式" size="mini" style="width: 150px;margin-right: 10px;">
						<el-option label="降序" value="desc"></el-option>
						<el-option label="升序" value="asc"></el-option>
					</el-select>
					<el-input v-model="searchForm.keyword" placeholder="输入图片名称" size="mini" style="margin-right: 10px;width: 150px;"></el-input>
					<el-button type="primary" size="mini"
					@click="getImageList">搜索</el-button>
				</div>
				<el-button type="success" size="mini"
				@click="cancelImgCheck()"
				v-if="checkImgList.length > 0">取消选中</el-button>
				<el-button type="success" size="mini" 
				@click="openAlbumModel(false)">创建相册</el-button>
				<el-button type="warning" size="mini"
				@click="uploadModel = true">上传图片</el-button>
				<el-button type="danger" size="mini"
				@click="multiDelImg({multiDel: true})">批量删除</el-button>
			</el-header>
			<el-container>
				<el-aside width="200px" style="position: absolute;top: 60px;left: 0;bottom: 60px;"
				class="bg-white border-right">
					<!-- 侧边 -->
					<ul class="list-group list-group-flush">
						<album-item :item="item" :index="index"
						v-for="(item,index) in albums" :key="index"
						:active="albumIndex === index"
						@change="albumChange"
						@edit="openAlbumModel"
						@del="delAlbum"></album-item>
					</ul>
				</el-aside>
				<el-container>
					<el-main style="position: absolute;top: 60px;left: 200px;bottom: 60px;right: 0;">
						<!-- 主内容 -->
						<el-row :gutter="10">
							<el-col :span="24" :lg="4" :md="6" :sm="8"
							v-for="(item,index) in imageList" :key="index">
								<el-card class="box-card mb-3 position-relative" 
								:body-style="{'padding':'0'}"
								shadow="hover"
								style="cursor: pointer;">
									<div class="border " 
									:class="{'border-danger': item.isChecked}">
										<span class="badge badge-danger"
										style="position: absolute;top: 0;right: 0;"
										v-if="item.isChecked">{{item.checkOrder}}</span>
										<div @click="choose(item)">
											<img :src="item.url" class="w-100"  />
											<div class="w-100 text-white px-1" style="background: rgba(0,0,0,0.5);margin-top: -25px;position: absolute;">
												<span class="small">{{item.name}}</span>
											</div>
										</div>
										<div class="p-2 text-center">
											<el-button-group>
											  <el-button class="p-2" size="mini" icon="el-icon-view"
											  @click="previewImg(item)"></el-button>
											  <el-button class="p-2" size="mini" icon="el-icon-edit"
											  @click="editImg(index, item)"></el-button>
											  <el-button class="p-2" size="mini" icon="el-icon-delete"
											  @click="multiDelImg({index: index, item})"></el-button>
											</el-button-group>
										</div>
									</div>
								</el-card>
							</el-col>
						</el-row>
					</el-main>
					
				</el-container>
			</el-container>
			<!-- footer -->
			<el-footer class="d-flex border-top align-items-center px-0">
				<div style="width: 200px;flex-shrink: 0;" class="h-100 d-flex align-items-center justify-content-center border-right">
					<el-button-group>
						<el-button size="mini" :disabled="albumPage === 1"
						@click="changeAlbumPage('pre')">上一页</el-button>
						<el-button size="mini"
						@click="changeAlbumPage('next')"
						:disabled="Math.ceil(albumTotall / 10) === albumPage">下一页</el-button>
					</el-button-group>
				</div>
				<div class="px-2" style="flex: 1;">
					<el-pagination
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
						:current-page="currentPage"
						:page-sizes="pageSizes"
						:page-size="pageSize"
						layout="total, sizes, prev, pager, next, jumper"
						:total="total">
					</el-pagination>
				</div>
			</el-footer>
			
			
		</el-container>
		<!-- 修改创建相册 -->
		<el-dialog :title="albumModelTitle" :visible.sync="albumModel">
			<el-form :model="albumForm" label-width="80px">
				<el-form-item label="相册名称">
					<el-input v-model="albumForm.name" placeholder="请输入相册名称" size="medium"></el-input>
				</el-form-item>
				<el-form-item label="排序">
					<el-input-number v-model="albumForm.order" :min="0" size="medium"></el-input-number>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="albumModel = false">取 消</el-button>
				<el-button type="primary" @click="confirmAlbumModel">确 定</el-button>
			</span>
		</el-dialog>
		
		<!-- 上传图片 -->
		<el-dialog title="上传图片" :visible.sync="uploadModel"
		@close="__initAlnums">
			<div class="text-center">
				<el-upload
				  class="upload-demo"
				  drag
				  action="/admin/image/upload"
				  :headers="{token: $store.state.user.token}"
				  :data="{image_class_id: image_class_id}"
				  name="img"
				  :on-success="uploadSuccess"
				  multiple>
				  <i class="el-icon-upload"></i>
				  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
				  <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
				</el-upload>
			</div>
		</el-dialog>
		
		<!-- 预览图片 -->
		<el-dialog :visible.sync="previewModel" width="70vw">
			<img :src="previewImgUrl" class="w-100"/>
		</el-dialog>
	</div>
</template>

<script>
import albumItem from "@/components/image/album-item.vue";
	
export default {
	inject: ['layout'],
	components: {
		albumItem,
	},
	
	data() {
		return {
			value: '',
			searchForm: {
				order: 'desc',
				keyword: ''
			},
			albums: [],
			albumTotall: 0,
			//相册当前页
			albumPage: 1,
			albumIndex: 3,
			albumModel: false,
			albumEditIndex: -1,
			albumForm: {
				name: '',
				order: 0
			},
			//上传图片model
			uploadModel: false,
			previewModel: false, //预览图片model
			previewImgUrl: '',
			//图片列表
			imageList: [],
			//选中的数组
			checkImgList: [],
			//当前页
			currentPage: 1,
			
			//pageSize每页数据条数
			pageSize: 10,
			pageSizes: [10,20,50,100],
			total: 0
			
		}
	},
	
	created() {
		this.__initAlnums()
	},
	
	computed: {
		albumModelTitle() {
			return this.albumEditIndex > -1 ? '修改相册' : '新增相册'
		},
		
		//选中相册的ID
		image_class_id() {
			let item = this.albums[this.albumIndex]
			if(item) {
				return item.id
			}
			return 0
		},
		
		//当前选中相册的图片列表URL
		getImageListUrl() {
			let other = ''
			if (this.searchForm.keyword !== '') {
				other = `&keyword=${this.searchForm.keyword}`
			}
			let searchUrl = `/admin/imageclass/${this.image_class_id}/image/${this.currentPage}?limit=${this.pageSize}&orer=${this.searchForm.order}${other}`
			console.log(searchUrl)
			return searchUrl
		}
	},
	
	methods: {
		//图片上传成功后的回调
		uploadSuccess(response, file, fileList) {
			console.log(response, file, fileList)
		},
		//相册分页功能
		changeAlbumPage(type) {
			if(type === 'pre') {
				if (this.albumPage > 0) this.albumPage--
			} else {
				this.albumPage++
			}
			this.__initAlnums()
		},
		
		//取消选中多个图片
		cancelImgCheck() {
			//imgList
			this.imageList.forEach(img => {
				//找到选中图片的索引
				let i = this.checkImgList.findIndex(item => item.id === img.id)
				if (i > -1) {
					img.isChecked = false
					img.checkOrder = 0
				}
			})
			this.checkImgList = []
		},
		//分页方法
		handleSizeChange(val) {
			this.pageSize = val
			this.getImageList()
		},
		handleCurrentChange(val) {
			this.currentPage = val
			this.getImageList()
		},
		//批量删除图片
		multiDelImg({multiDel = false, index, item}) {
			
			this.$confirm('确定删除选中图片?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.layout.showLoading()
				if(multiDel) {
					if(this.checkImgList.length === 0) {
						return this.$message({
							message: '您还没有选中的图片',
							type: 'error'
						});
					}
					// this.imageList = this.imageList.filter(img => {
					// 	return !this.checkImgList.some(v => v.id === img.id)
					// })
					// this.checkImgList = []
					let ids = this.imageList.map(v => v.id)
					this.axios.post('/admin/image/delete_all', {ids: ids}, {token: true})
						.then(res => {
							this.$message({
								message: '删除成功',
								type: 'success'
							})
							this.__initAlnums()
							this.checkImgList = []
							this.layout.hideLoading()
						})
						.catch(err => {
							this.layout.hideLoading()
						})
				} else { //删除单张图片
					this.axios.delete('/admin/image/' + item.id, {token: true})
						.then(res => {
							this.__initAlnums()
							this.layout.hideLoading()
							this.$message({
								message: '删除图片成功',
								type: 'success'
							})
						})
						.catch(err => {
							this.layout.hideLoading()
						})
				}
			}).catch(() => {
				this.$message({
				type: 'info',
				message: '已取消删除'
				});
			});
			
		},
		
		//选中图片
		choose(item) {
			if (!item.isChecked) { //之前没有选中
				this.checkImgList.push({
					id: item.id,
					url: item.url
				})
				item.checkOrder = this.checkImgList.length
				item.isChecked = true
			} else if (item.isChecked) { //之前已经选中，取消选中
				//找到在选中列表中的索引
				let i = this.checkImgList.findIndex(v => v.id === item.id)
				if (i === -1) return
				//重新计算序号
				//是否是最后一个
				let len = this.checkImgList.length
				if (i + 1 < len) { //不是最后一个
					for (let j = i; j < len; j++) {
						let no = this.imageList.findIndex(v => v.id === this.checkImgList[j].id)
						if(no > -1) {
							this.imageList[no].checkOrder--
						}
					}
				}
				this.checkImgList.splice(i, 1)
				item.isChecked = false
				item.checkOrder = 0
			}
			
		},
		//删除图片
		delImg(index) {
			this.$confirm('此操作将永久删除该图片, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.imageList.splice(index, 1)
				this.$message({
				type: 'success',
				message: '删除成功!'
				});
			}).catch(() => {
				this.$message({
				type: 'info',
				message: '已取消删除'
				});
			});
		},
		
		//修改图片名称
		editImg(index,item) {
			this.$prompt('请输入图片名称', '提示', {
			  confirmButtonText: '确定',
			  cancelButtonText: '取消',
			  inputPattern: /\s*\S+?/,
			  inputErrorMessage: '图片名称不能为空',
			  inputValue: item.name
			}).then(({ value }) => {
				this.layout.showLoading()
				this.axios.post('/admin/image/' + item.id, {name: value}, {token: true})
					.then(res => {
						this.layout.hideLoading()
						this.$message({
							type: 'success',
							message: '修改图片名称成功'
						});
						item.name = value
						//初始化方法，用调用吗？
						// this.__initAlnums()
					})
					.catch(err => {
						this.layout.hideLoading()
					})
				
				
			}).catch(() => {
			  this.$message({
				type: 'info',
				message: '取消输入'
			  });       
			});
		},
		
		//获取对应相册下的图片列表
		getImageList() {
			this.layout.showLoading()
			//获取相册列表
			this.axios.get(this.getImageListUrl, {token: true})
				.then(res => {
					let result = res.data.data
					this.imageList = result.list.map(item => {
						return {
							id: item.id,
							url: item.url,
							name: item.name,
							ischeck: false,
							checkOrder:0
						}
					})
					this.total = result.totalCount
					this.layout.hideLoading()
				}).catch(err => {
					this.layout.hideLoading()
				})
		},
		
		__initAlnums() {
			this.layout.showLoading()
			this.axios.get('/admin/imageclass/' + this.albumPage, {token: true})
				.then(res => {
					let result = res.data.data
					this.albums = result.list
					this.albumTotall = result.totalCount
					//获取选中相册下第一页的相册列表
					this.getImageList()
					this.layout.hideLoading()
				}).catch(err => {
					this.layout.hideLoading()
				})
			
		},
		//切换相册
		albumChange(index) {
			if(index !== this.albumIndex) {
				this.albumIndex = index
				this.getImageList()
			}
		},
		//删除相册
		delAlbum(index) {
			
			this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				let id = this.albums[index].id
				this.layout.showLoading()
				this.axios.delete('/admin/imageclass/' + id, {token: true})
					.then(res => {
						this.$message({
						type: 'success',
						message: '删除成功!'
						});
						this.__initAlnums()
						this.layout.hideLoading()
					})
					.catch(err => {
						this.layout.hideLoading()
					})
				this.albums.splice(index,1)
				
			}).catch(() => {
				this.$message({
				type: 'info',
				message: '已取消删除'
				});
			});
		},
		//打开相册 修改 ｜ 新增model
		openAlbumModel({index, item}) {
			//修改
			if(item) {
				this.albumForm.name = item.name
				this.albumForm.order = item.order
				this.albumEditIndex = index
				return this.albumModel = true
			}
			//创建相册
			this.albumForm = {name: '', order: 0}
			this.albumEditIndex = -1
			this.albumModel = true
		},
		
		//修改相册
		updateAlbum() {
			let item = this.albums[this.albumEditIndex]
			this.layout.showLoading()
			this.axios.post('/admin/imageclass/' + item.id, this.albumForm, {token: true})
				.then(res => {
					this.layout.hideLoading()
					this.__initAlnums()
					this.$message({
						type: 'success',
						message: '修改相册成功'
					})
				})
				.catch(err => {
					this.layout.hideLoading()
				})
			// this.albums[this.albumEditIndex].name = this.albumForm.name
			// this.albums[this.albumEditIndex].order = this.albumForm.order
		},
		
		//点击确定修改 ｜ 新增相册
		confirmAlbumModel() {
			//判断是否是修改
			if(this.albumEditIndex > -1) {
				this.updateAlbum()
				return this.albumModel = false
			}
			if(!this.albumForm.name || this.albumForm.name.trim() === '') {
				return this.$message({
					message: '相册名称不能为空',
					type: 'error'
				})
			}
			//创建相册
			this.layout.showLoading()
			this.axios.post('/admin/imageclass', this.albumForm, {token: true})
				.then(res => {
					this.albumModel = false
					this.layout.hideLoading()
					this.$message({
						type: 'success',
						message: '创建相册成功'
					})
					this.__initAlnums()
				}).catch(err => {
					this.layout.hideLoading()
				})
			this.albumModel = false
		},
		
		//点击预览图片
		previewImg(item) {
			this.previewModel = true
			this.previewImgUrl = item.url
		}
		
	}
}
</script>

<style>

</style>
